package com.mgface.zookeeper.premitive;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;

public class 负载均衡_动态DNS {

	public static void main(String[] args) throws Exception {
		String root = "/DDNS";
		String app1 = ZKPaths.makePath(root, "/app1");
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString("localhost:2181,localhost:2182,localhost:2183").sessionTimeoutMs(10_000)
				.connectionTimeoutMs(10_000).retryPolicy(new ExponentialBackoffRetry(1_000, 3)).build();
		client.start();
		System.out.println("启动完毕...");
		ZKPaths.mkdirs(client.getZookeeperClient().getZooKeeper(), app1);
		String path = client.create().withMode(CreateMode.EPHEMERAL).forPath("/server.app1.com");
		final NodeCache cache = new NodeCache(client, path, false);
		cache.start(true);
		cache.getListenable().addListener(() -> {
			System.out.println(Thread.currentThread().getName());
			ChildData childData = cache.getCurrentData();
			if (childData == null) {
				System.out.println("===delete, path=" + path + ", childData=" + childData);
			} else {
				System.out.println("===update or add, path=" + path + ", childData="+ new String(childData.getData()));
			}
		}, Executors.newFixedThreadPool(4));
		// 设置当前值
		client.setData().forPath(path, "127.0.0.1:8080".getBytes());
		client.setData().forPath(path, "127.0.0.1:8080,127.0.0.1:9090".getBytes());
		TimeUnit.SECONDS.sleep(60);
		cache.close();
	}

}
